package com.happyface.andquiz;

import java.io.InvalidObjectException;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.happyface.andquiz.internals.Question;
import com.happyface.andquiz.internals.Questions;
import com.sileria.android.SlidingTray;

public class NewGameActivity extends Activity {

    static final int DIALOG_PAUSED_ID = 0;
    static final int DIALOG_GAMEOVER_ID = 1;
    static final int DIALOG_SPECIALIST_ID = 2;

    private static final int EASY_QUESTION_VALUE = 100;
    private static final int MEDIUM_QUESTION_VALUE = 500;
    private static final int HARD_QUESTION_VALUE = 1000;

    private static final int QUESTION_COUNTDOWN = 10000;

    private Button btnBack;
    private Button btn25Percent;
    private Button btnAskSpecialist;
    private Button btnBypass;

    private Button btnOptionA;
    private Button btnOptionB;
    private Button btnOptionC;
    private Button btnOptionD;

    private TextView txtViewQuestion;
    private TextView txtViewQuestionCountdown;

    private Context context;
    /**
     * counter to monitor how many times the 25Percent button is clicked
     */
    private int timesPercentUsed;
    /**
     * the current game score
     */
    private int score;
    /**
     * the number of questions the user has answered
     */
    private int questionNumber;
    /**
     * the current question
     */
    private Question question;
    /**
     * the answer to the current question
     */
    private String questionAnswer;
    /**
     * the list of questions
     */
    private Questions listOfQuestions;
    /**
     * the specialist dialog
     */
    private Dialog specialistDialog;
    /**
     * the game over dialog
     */
    private Dialog gameOverDialog;
    /**
     * the count down timer
     */
    private CountDownTimer countdown;
    /**
     * boolean to determine whether to stop the counter
     */
    private boolean stopCountdown;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
	setContentView(R.layout.new_game_layout);

	this.context = this;
	getControls();
	initActions();

	startNewGame();
    }    

    @Override
    public void onBackPressed() {
	// TODO Auto-generated method stub
	super.onBackPressed();
	countdown.cancel();
    }



    @Override
    protected Dialog onCreateDialog(int id) {
	switch (id) {
	case DIALOG_PAUSED_ID:
	    // do the work to define the pause Dialog
	    return null;
	case DIALOG_GAMEOVER_ID:
	    // code to define the game over Dialog
	    gameOverDialog = new Dialog(context);
	    gameOverDialog.setCancelable(false);

	    gameOverDialog.setContentView(R.layout.gameover_dialog_layout);
	    gameOverDialog.setTitle("Game Over");

	    TextView txtViewGameOverMessage = (TextView) gameOverDialog
		    .findViewById(R.id.txtViewGameOverMessage);
	    txtViewGameOverMessage.setText("Esti prost mai invata !!!");

	    Button btnBackToMain = (Button) gameOverDialog
		    .findViewById(R.id.btnBackToMain);
	    Button btnSendScore = (Button) gameOverDialog
		    .findViewById(R.id.btnSendScore);
	    Button btnNewGame = (Button) gameOverDialog
		    .findViewById(R.id.btnNewGame);

	    btnBackToMain.setOnClickListener(new OnClickListener() {

		public void onClick(View v) {
		    gameOverDialog.dismiss();
		    NewGameActivity.this.finish();
		}
	    });

	    btnNewGame.setOnClickListener(new OnClickListener() {

		public void onClick(View v) {
		    gameOverDialog.dismiss();
		    startNewGame();
		}
	    });

	    btnSendScore.setOnClickListener(new OnClickListener() {

		public void onClick(View v) {
		}
	    });
	    return gameOverDialog;
	case DIALOG_SPECIALIST_ID:
	    // code to define the specialist Dialog
	    specialistDialog = new Dialog(context);
	    specialistDialog.setCancelable(false);

	    specialistDialog.setContentView(R.layout.specialist_dialog_layout);
	    specialistDialog.setTitle("Specialistul spune :");

	    View rootLayout = specialistDialog.findViewById(R.id.btnDismiss);
	    rootLayout.setOnClickListener(new OnClickListener() {

		public void onClick(View v) {
		    specialistDialog.dismiss();
		}
	    });
	    ImageView image = (ImageView) specialistDialog
		    .findViewById(R.id.image);
	    image.setImageResource(R.drawable.ic_launcher);
	    return specialistDialog;
	default:
	    return null;
	}
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
	// TODO Auto-generated method stub
	super.onPrepareDialog(id, dialog);

	switch (id) {
	case DIALOG_SPECIALIST_ID:
	    TextView txtViewSpecialistAnswer = (TextView) dialog
		    .findViewById(R.id.txtViewSpecialistAnswer);
	    String specialistAnswer = null;
	    boolean notDisabled = false;
	    while (!notDisabled) {
		specialistAnswer = question
			.askTheSpecialist(EASY_QUESTION_VALUE);

		if ((specialistAnswer.equals(btnOptionA.getText().toString()) && btnOptionA
			.isEnabled())
			|| (specialistAnswer.equals(btnOptionB.getText()
				.toString()) && btnOptionB.isEnabled())
			|| (specialistAnswer.equals(btnOptionC.getText()
				.toString()) && btnOptionC.isEnabled())
			|| (specialistAnswer.equals(btnOptionD.getText()
				.toString()) && btnOptionD.isEnabled())) {
		    notDisabled = true;
		}
	    }

	    txtViewSpecialistAnswer.setText(specialistAnswer);
	    break;

	case DIALOG_GAMEOVER_ID:
	    TextView txtViewScore = (TextView) dialog
		    .findViewById(R.id.txtViewScore);
	    txtViewScore.setText(Integer.toString(score));
	default:
	    break;
	}
    }

    /**
     * Initializes everything
     */
    private void startNewGame() {

	timesPercentUsed = 0;
	score = 0;
	questionNumber = 0;
	listOfQuestions = new Questions("questions/easyquestions.txt", this);
	listOfQuestions.load();

	initControls();
	setNextQuestion();
	AdaugaDrawer();
    }

    /**
     * Get references to layout controls
     */
    private void getControls() {
	btnBack = (Button) findViewById(R.id.btnBack);
	btn25Percent = (Button) findViewById(R.id.btn25Percent);
	btnAskSpecialist = (Button) findViewById(R.id.btnAskSpecialist);
	btnBypass = (Button) findViewById(R.id.btnBypass);

	btnOptionA = (Button) findViewById(R.id.btnOptionA);
	btnOptionB = (Button) findViewById(R.id.btnOptionB);
	btnOptionC = (Button) findViewById(R.id.btnOptionC);
	btnOptionD = (Button) findViewById(R.id.btnOptionD);

	txtViewQuestion = (TextView) findViewById(R.id.txtViewQuestion);
	txtViewQuestionCountdown = (TextView) findViewById(R.id.txtViewCountdown);
    }

    /**
     * Initialize the layout controls
     */
    private void initControls() {
	btn25Percent.setEnabled(true);
	btnAskSpecialist.setEnabled(true);
	btnBypass.setEnabled(true);

	btnOptionA.setEnabled(true);
	btnOptionB.setEnabled(true);
	btnOptionC.setEnabled(true);
	btnOptionD.setEnabled(true);
    }

    /**
     * Initialize actions for layout controls
     */
    private void initActions() {
	// action for button OptionA
	btnOptionA.setOnClickListener(new OnClickListener() {

	    public void onClick(View v) {
		Log.d("THEO", questionAnswer + btnOptionA.getText().toString());
		// if optionA is the correct answer
		if (questionAnswer.equals(btnOptionA.getText().toString())) {
		    onCorrectAnswer();
		} else {
		    onWrongAnswer();
		}
	    }
	});
	// action for button OptionB
	btnOptionB.setOnClickListener(new OnClickListener() {

	    public void onClick(View v) {
		// if optionB is the correct answer
		if (questionAnswer.equals(btnOptionB.getText().toString())) {
		    onCorrectAnswer();
		} else {
		    onWrongAnswer();
		}
	    }
	});
	// action for button OptionC
	btnOptionC.setOnClickListener(new OnClickListener() {

	    public void onClick(View v) {
		// if optionC is the correct answer
		if (questionAnswer.equals(btnOptionC.getText().toString())) {
		    onCorrectAnswer();
		} else {
		    onWrongAnswer();
		}
	    }
	});
	// action for button OptionD
	btnOptionD.setOnClickListener(new OnClickListener() {

	    public void onClick(View v) {
		// if optionD is the correct answer
		if (questionAnswer.equals(btnOptionD.getText().toString())) {
		    onCorrectAnswer();
		} else {
		    onWrongAnswer();
		}
	    }
	});

	// action for button 25Percent
	btn25Percent.setOnClickListener(new OnClickListener() {

	    public void onClick(View v) {
		String percentResult = question.do25Percent();
		Log.d("THEO", percentResult);
		if (btnOptionA.getText().toString().equals(percentResult)) {
		    btnOptionA.setEnabled(false);
		}
		if (btnOptionB.getText().toString().equals(percentResult)) {
		    btnOptionB.setEnabled(false);
		}
		if (btnOptionC.getText().toString().equals(percentResult)) {
		    btnOptionC.setEnabled(false);
		}
		if (btnOptionD.getText().toString().equals(percentResult)) {
		    btnOptionD.setEnabled(false);
		}
		timesPercentUsed++;
		if (timesPercentUsed == 2) {
		    btn25Percent.setEnabled(false);
		}
	    }
	});
	// action for button AskSpecialist
	btnAskSpecialist.setOnClickListener(new OnClickListener() {

	    // show specialist dialog
	    public void onClick(View v) {
		showDialog(DIALOG_SPECIALIST_ID);
		btnAskSpecialist.setEnabled(false);
	    }
	});

	// action for button Bypass/Skip
	btnBypass.setOnClickListener(new OnClickListener() {

	    public void onClick(View v) {
		// stop current countdown
		countdown.cancel();
		
		// go to next question
		setNextQuestion();
		btnBypass.setEnabled(false);
	    }
	});
    }

    int secondsLeft = 0;
    /**
     * Gets a new question and updates the UI
     */
    private void setNextQuestion() {
	secondsLeft = 0;
	countdown = new CountDownTimer(QUESTION_COUNTDOWN, 100) {

	    @Override
	    public void onTick(long millisUntilFinished) {
		if (Math.round((float)millisUntilFinished / 1000.0f) != secondsLeft)
	         {  
	             secondsLeft = Math.round((float)millisUntilFinished / 1000.0f);
	             txtViewQuestionCountdown.setText(""+ secondsLeft);
	         }
		
	    }

	    @Override
	    public void onFinish() {
		txtViewQuestionCountdown.setText(Integer.toString(0));
		showDialog(DIALOG_GAMEOVER_ID);
	    }
	}.start();
	btnOptionA.setEnabled(true);
	btnOptionB.setEnabled(true);
	btnOptionC.setEnabled(true);
	btnOptionD.setEnabled(true);

	try {
	    question = listOfQuestions.getRandomQuestion();
	    questionAnswer = question.getCorrectAnswer();
	    if (question == null) {
		Toast.makeText(this, "No more questions available",
			Toast.LENGTH_SHORT).show();
	    } else {
		questionNumber++;

		txtViewQuestion.setText(question.getQuestionText());
		btnOptionA.setText(question.getOptionA());
		btnOptionB.setText(question.getOptionB());
		btnOptionC.setText(question.getOptionC());
		btnOptionD.setText(question.getOptionD());
	    }
	} catch (InvalidObjectException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
    }

    /**
     * Called when the user gives the correct answer to the question
     */
    private void onCorrectAnswer() {
	Toast.makeText(NewGameActivity.this, "Correct answer",
		Toast.LENGTH_SHORT).show();
	
	// stop countdown
	countdown.cancel();

	// update score
	updateScore(EASY_QUESTION_VALUE);

	// set up the next question
	setNextQuestion();
    }

    /**
     * Called then the user gives the wrong answer to the question
     */
    private void onWrongAnswer() {
	// stop countdown
	countdown.cancel();
	
	showDialog(DIALOG_GAMEOVER_ID);
    }

    /**
     * Updates the score with the value the question is worth
     * 
     * @param questionValue
     *            the value the question is worth
     */
    private void updateScore(int questionValue) {
	this.score += questionValue;
    }

    private void AdaugaDrawer() {

	Button handle = new Button(this);
	handle.setText("<");

	// content
	LinearLayout lnFundalDrawer = new LinearLayout(this);
	lnFundalDrawer.setOrientation(LinearLayout.VERTICAL);
	lnFundalDrawer.setPadding(5, 2, 5, 2);
	lnFundalDrawer.setBackgroundColor(Color.BLUE);
	lnFundalDrawer.setGravity(Gravity.CENTER);

	TextView content = new TextView(this);
	content.setText("SUGI PULA BAAA");
	content.setTextColor(0xffffffff);

	lnFundalDrawer.addView(content);

	// drawer
	SlidingTray drawer = new SlidingTray(this, handle, lnFundalDrawer,
		SlidingTray.RIGHT);

	LinearLayout lnDrawer = (LinearLayout) findViewById(R.id.linearLayoutDrawer);
	lnDrawer.addView(drawer);
    }
}
